<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文章关键字" prop="articleKeywords">
        <el-input
          v-model="queryParams.articleKeywords"
          placeholder="请输入文章关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="序号" prop="serialNumber">
        <el-input
          v-model="queryParams.serialNumber"
          placeholder="请输入序号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:microcircle:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:microcircle:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:microcircle:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="microcircleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="微圈id" align="center" prop="id" />
      <el-table-column label="用户id" align="center" prop="userId" />
      <el-table-column label="文章图片" align="center" prop="articleUrls" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.articleUrls" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="releaseTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.releaseTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否显示" align="center" prop="isShow">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isShow"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="2"
            :inactive-value="3"
            @change="handleChangeisShow(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="序号" align="center" prop="serialNumber" />
      <el-table-column label="状态" align="center" prop="details" :formatter="formatDetails">
      </el-table-column>
      <el-table-column label="文章收藏量统计" align="center" prop="collectionNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSelect(scope.row)"
            v-hasPermi="['system:microcircle:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:microcircle:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:microcircle:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改微圈对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文章关键字" prop="articleKeywords">
          <el-input v-model="form.articleKeywords" placeholder="请输入文章关键字" />
        </el-form-item>
        <el-form-item label="文章图片" prop="articleUrls">
          <image-upload v-model="form.articleUrls"/>
        </el-form-item>
        <el-form-item label="发布时间" prop="releaseTime">
          <el-date-picker clearable
            v-model="form.releaseTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否显示" prop="isShow">
            <el-radio v-model="radio" label="2">显示</el-radio>
            <el-radio v-model="radio" label="3">隐藏</el-radio>
        </el-form-item>
        <el-form-item label="序号" prop="serialNumber">
          <el-input v-model="form.serialNumber" placeholder="请输入序号" />
        </el-form-item>
        <el-form-item label="文章内容">
          <editor v-model="form.articleContent" :min-height="192"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看微圈对话框 -->
    <el-dialog :title="title" :visible.sync="viewOpen" width="1000px" append-to-body custom-class="view-dialog">
      <el-descriptions class="margin-top" :column="3" :size="size" border>
        <el-descriptions-item label="用户id">{{ form.userId }}</el-descriptions-item>
        <el-descriptions-item label="文章关键字">{{ form.articleKeywords }}</el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ form.releaseTime }}</el-descriptions-item>
        <el-descriptions-item label="序号">{{ form.serialNumber }}</el-descriptions-item>
        <el-descriptions-item label="是否显示">
          <el-radio v-model="form.isShow" label="2" disabled>显示</el-radio>
          <el-radio v-model="form.isShow" label="3" disabled>隐藏</el-radio>
        </el-descriptions-item>
        <el-descriptions-item label="状态">{{ form.details }}</el-descriptions-item>
        <el-descriptions-item label="文章点击数量">{{ form.articleHits }}</el-descriptions-item>
        <el-descriptions-item label="文章点赞数量">{{ form.articleLike }}</el-descriptions-item>
        <el-descriptions-item label="文章评论数量">{{ form.articleReviews }}</el-descriptions-item>
        <el-descriptions-item label="文章分享数量">{{ form.articleShare }}</el-descriptions-item>
        <el-descriptions-item label="文章收藏量统计">{{ form.collectionNum }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions class="margin-top" :column="2" :size="size" border>
        <el-descriptions-item label="文章图片路径">
          <image-preview :src="form.articleUrls" :width="200" :height="200"/>
        </el-descriptions-item>
      </el-descriptions>

      <div>
        <h3>文章内容</h3>
        <div v-html="form.articleContent"></div>
      </div>

      <!-- 他人评论区块 -->
      <div>
        <h3>评论</h3>
        <el-table
          v-loading="loading"
          :data="comments"
          row-key="id"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          style="width: 100%"
          height="400"
          border
        >
          <el-table-column label="回复人" width="150" align="center" prop="username" fixed />
          <el-table-column label="头像" width="100" align="center" prop="avatar">
            <template slot-scope="scope">
              <image-preview :src="scope.row.avatar" :width="50" :height="50"/>
            </template>
          </el-table-column>
          <el-table-column label="回复内容" align="center" prop="content" >
            <template slot-scope="scope">
              <div v-html="scope.row.content"></div>
            </template>
          </el-table-column>
          <el-table-column label="回复时间戳" align="center" prop="replytime" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.replytime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
             <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-chat-dot-square"
                  @click="toggleReply(scope.row)"
                >回复</el-button>
             </template>
          </el-table-column>
        </el-table>
      </div>
      <!--回复评论-->
      <div v-for="row in microcircleList" :key="row.id">
        <div v-if="replyStates[row.id]">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入评论"
            v-model="comment"
          />
          <el-button type="primary" @click="addComment(row.id)">提交评论</el-button>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listMicrocircle, getMicrocircle, delMicrocircle, addMicrocircle, updateMicrocircle } from "@/api/siyun/microcircle";
import { getUserProfile } from "@/api/system/user"
import { listComment2, addComment } from "@/api/comment/comment.js";

export default {
  name: "Microcircle",
  data() {
    return {
      userProfile: [],
      //评论
      comment: '',
      comments: [],
      //查看页面
      viewOpen: false,
      // 单选框
      radio: 2,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 微圈表格数据
      microcircleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        articleKeywords: null,
        articleUrls: null,
        createDate: null,
        releaseTime: null,
        articleHits: null,
        articleLike: null,
        articleReviews: null,
        articleShare: null,
        isShow: null,
        serialNumber: null,
        articleContent: null,
        updateUser: null,
        updateDate: null,
        details: null,
        collectionNum: null
      },
      commentParams: {
        commentId: null,
        type: 1
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      size: "medium",
      // 添加回复状态
      replyStates: {}
    };
  },
  created() {
    this.getList();
    this.getUser();
  },
  methods: {
    getUser() {
      getUserProfile().then(response => {
        console.log(response);
        this.userProfile = response.data;
      })
    },
    getComment() {
      this.comments = []; // 清空 comments 数组
      listComment2(this.commentParams).then(response => {
        this.comments = this.handleTree(response.data, "id", "pid");
      }).catch(error => {
        console.error("获取评论信息失败:", error);
        this.$modal.msgError("获取评论信息失败，请稍后再试");
      });
    },
    handleTree(data, id, pid) {
      const map = {};
      const result = [];
      data.forEach(item => {
        map[item[id]] = { ...item, children: [] };
      });
      data.forEach(item => {
        if (item[pid] !== null && map[item[pid]]) {
          map[item[pid]].children.push(map[item[id]]);
        } else {
          result.push(map[item[id]]);
        }
      });
      return result;
    },
    // 评论
    addComment(pid) {
      if (this.comment.trim() === '') {
        this.$message.warning('未书写评论内容');
        return;
      }
      const newComment = {
        userId: this.userProfile.userId, // 假设 userProfile 包含当前用户的 userId
        content: this.comment,
        pid: pid
      };
      addComment(newComment).then(response => {
        this.$message.success('评论成功');
        this.comment = ''; // 清空评论框
        this.getComment(); // 重新获取评论数据
      }).catch(error => {
        console.error("提交评论失败:", error);
        this.$message.error("提交评论失败，请稍后再试");
      });
    },

    // 切换回复状态
    toggleReply(row) {
      this.$set(this.replyStates, row.id, !this.replyStates[row.id]);
    },
    handleChangeisShow(row) {
      const newStatus = row.isShow === 2 ? 2 : 3;
      updateMicrocircle({ id: row.id, isShow: newStatus })
        .then(response => {
          this.msgSuccess("状态更新成功");
          this.getList(); // 刷新列表以反映最新状态
        })
        .catch(error => {
          this.msgError("状态更新失败");
          row.isShow = row.isShow === 2 ? 3 : 2; // 回滚状态
        });
    },
    //查询按钮
    handleSelect(row) {
      this.reset();
      const id = row.id;
      this.commentParams.commentId = id; // 设置 commentId
      this.getComment(); // 获取评论数据
      getMicrocircle(id).then(response => {
        this.form = response.data;
        this.viewOpen = true;
        this.title = "查看微圈";
      }).catch(error => {
        console.error("获取微圈信息失败:", error);
        this.$modal.msgError("获取微圈信息失败，请稍后再试");
      });
    },
    formatDetails(row) {
      const statusMap = {
        1: '草稿',
        2: '已通过',
        3: '退回',
      };
      return statusMap[row.details] || '未知';
    },
    /** 查询微圈列表 */
    getList() {
      this.loading = true;
      listMicrocircle(this.queryParams).then(response => {
        this.microcircleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        articleKeywords: null,
        articleUrls: null,
        createDate: null,
        releaseTime: null,
        articleHits: null,
        articleLike: null,
        articleReviews: null,
        articleShare: null,
        isShow: null,
        serialNumber: null,
        articleContent: null,
        updateUser: null,
        updateDate: null,
        details: null,
        collectionNum: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加微圈";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMicrocircle(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改微圈";
      });
    },
    getCurrentTime() {
        const now = new Date();
        return now.toISOString().slice(0, 19).replace('T', ' ');
    },
  /** 提交按钮 */
  submitForm() {
    this.$refs["form"].validate(valid => {
      if (valid) {
        if (this.form.id != null) {
          this.form.updateUser = this.userProfile.userId; // 修正这里
          this.form.updateDate = this.getCurrentTime();
          this.form.details = 3;
          updateMicrocircle(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        } else {
          this.form.userId = this.userProfile.userId; // 修正这里
          this.form.createDate = this.getCurrentTime();
          this.form.details = 3;
          addMicrocircle(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      }
    });
  },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除微圈编号为"' + ids + '"的数据项？').then(function() {
        return delMicrocircle(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/microcircle/export', {
        ...this.queryParams
      }, `microcircle_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.comment-item {
  display: flex;
  margin-bottom: 16px;
}

.comment-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 16px;
}

.avatar-img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-user {
  margin-top: 8px;
  font-weight: bold;
}

.comment-content {
  flex: 1;
}
</style>

